package com.bx.implatform.growUp.utils;

import com.bx.implatform.enums.ResultCode;
import com.bx.implatform.growUp.exception.GrowUpException;
import com.bx.implatform.util.BaseExternalApiService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Service
public class GrowUpExternalApiService extends BaseExternalApiService {

    public GrowUpExternalApiService(@Qualifier("growUpRestTemplate") RestTemplate restTemplate) {
        super(restTemplate);
    }


    // GET 请求（参数拼接在 URL 上）
    public <T> T get(String url, Class<T> responseType, Object... uriVariables) {
        // 如果外部系统要求 GET 请求的签名参数放在 URL 上，可以在这里处理
        return restTemplate.getForObject(url, responseType, uriVariables);
    }

    @Override
    public <T> T post(String url, Object requestBody, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(requestBody instanceof MultiValueMap ?
                MediaType.MULTIPART_FORM_DATA : MediaType.APPLICATION_JSON);
        try {
            return restTemplate.postForObject(url, new HttpEntity<>(requestBody, headers), responseType);
        } catch (HttpServerErrorException e) {
            // 解析第三方错误信息
            String errorBody = e.getResponseBodyAsString();
            // 尝试提取业务错误信息
            String bizError = extractBizMessage(errorBody);
            throw new GrowUpException(
                    ResultCode.PROGRAM_ERROR.getCode(),
                    "第三方服务返回错误: " + bizError,
                    errorBody
            );
        } catch (RestClientException e) {
            throw new GrowUpException(
                    ResultCode.PROGRAM_ERROR.getCode(),
                    "服务通信失败: " + e.getMessage(),
                    null
            );
        }
    }

    // 从嵌套JSON中提取业务错误
    private String extractBizMessage(String json) {
        try {
            JsonNode node = new ObjectMapper().readTree(json);
            if (node.has("message")) {
                String message = node.get("message").asText();
                // 处理嵌套JSON字符串
                if (message.contains("\"msg\":")) {
                    JsonNode innerNode = new ObjectMapper().readTree(message.replace("\"", ""));
                    return innerNode.path("msg").asText();
                }
                return message;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未知错误";
    }

    // POST 请求（参数放在请求体）
    public <T> T post(String url, Object requestBody, Class<T> responseType, String userId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("User-Id", userId);
        HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers);

        return restTemplate.postForObject(url, requestEntity, responseType);
    }

}